package com.zhilianbao.leyaogo.ui.fragment.me.userinfo;

import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextWatcher;
import android.widget.TextView;

import com.bql.utils.CheckUtils;
import com.zhilianbao.leyaogo.R;
import com.zhilianbao.leyaogo.constants.IntentConfig;
import com.zhilianbao.leyaogo.ui.fragment.base.BaseOkHttpFragment;
import com.zhilianbao.leyaogo.utils.XToastUtils;
import com.zhilianbao.leyaogo.view.widgets.AwesomeEditTextView;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * ClassName: EditInfoFragment <br>
 * Description: 编辑信息Fragment<br>
 * Author: Cyarie <br>
 * Created: 2016/9/30 11:17 <br>
 * Update Time：<br>
 * Update Description：<br>
 */
public class EditInfoFragment extends BaseOkHttpFragment {


    @BindView(R.id.et_info)
    AwesomeEditTextView mEtInfo;
    @BindView(R.id.tv_input_save)
    TextView mTvInputSave;

    private int type;//0 昵称 1 个性签名 2 我的地址 3 用户名

    private String value;

    private String right;

    //输入表情前的光标位置
    private int cursorPos;
    //输入表情前EditText中的文本
    private String inputAfterText;
    //是否重置了EditText的内容
    private boolean resetText;
    private String mText;

    /**
     * 修改用户信息
     *
     * @param type 0 昵称 1 个性签名 2 我的地址
     * @return
     */
    public static EditInfoFragment getInstance(int type, String value) {
        EditInfoFragment fragment = new EditInfoFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(IntentConfig.USER_EDIT_USER_TYPE, type);
        bundle.putString(IntentConfig.USER_EDIT_USER_VALUE, value);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.fragment_edit_info;
    }

    @Override
    protected void initToolbarHere() {
        if (getArguments() != null) {
            type = getArguments().getInt(IntentConfig.USER_EDIT_USER_TYPE, 0);
            value = getArguments().getString(IntentConfig.USER_EDIT_USER_VALUE, "");
            switch (type) {
                case 0:
                    initData(getString(R.string.user_name_title), getString(R.string.main_me), type, value, "请输入昵称");
                    break;
                case 1:
                    initData(getString(R.string.signature_title), getString(R.string.main_me), type, value, "请输入个性签名");
                    break;
                //                case 2:
                //                    initData(getString(R.string.my_address_title), getString(R.string.main_me), getString(R.string.sure), type, value);
                //                    break;
            }
        }
    }

    @Override
    protected void initViewsAndEvents(Bundle savedInstanceState) {
//        initEditText();
        mEtInfo.setFilterEmoji(true);
    }

    /**
     * 初始化数据
     *
     * @param title 标题
     * @param left  左边文字
     * @param type  修改类型
     * @param info  修改信息
     * @param hint  提示信息
     * @param
     */
    private void initData(String title, String left, int type, String info, String hint) {
        initToolbar(title);
        mEtInfo.setText(info);
        mEtInfo.setHint(hint);
        if (type != 2)
            mEtInfo.setFilters(new InputFilter[]{new InputFilter.LengthFilter(20)});
    }
//
//    @Override
//    public void btnRightTextClick() {
//        super.btnRightTextClick();
//
//    }

    /**
     * 设置编辑结果
     */
    private void setResult(boolean canNull, String info) {
        if (!canNull) {
            if (CheckUtils.isEmpty(info)) {
                XToastUtils.showShortToast(type == 0 ? "昵称不能为空" : "个性签名不能为空");
                return;
            }
        }
        Bundle bundle = new Bundle();
        bundle.putString(IntentConfig.USER_EDIT_USER_INFO, mEtInfo.getText().toString().trim());
        setFramgentResult(type, bundle);
        pop();
    }

    @Override
    public boolean isInjectSkinView() {
        return true;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        hideSoftInput();
    }

    @OnClick(R.id.tv_input_save)
    public void onClick() {
        //保存用户名
        if (type == 3 && CheckUtils.equalsString(right, getString(R.string.invoice_save))) {
            if (CheckUtils.isEmpty(mEtInfo.getText().toString().trim())) {
                XToastUtils.showShortToast("用户名不能为空");
            } else {
//                AccountApi.updateUserAlias(mActivity, mEtInfo.getText().toString().trim(), new DialogCallback<Object>(mActivity, Object.class) {
//                    @Override
//                    public void onResponse(boolean isFromCache, Object o, Request request, @Nullable Response response) {
//                        XToastUtils.showShortToast("用户名修改成功");
//                        Utils.updateUserAlisa(mEtInfo.getText().toString().trim());
//                        EventBus.getDefault().post(new EventManager(UserEventCode.MSG_CODE_MODIFY_ALIAS));
//                        pop();
//                    }
//                });
            }
        } else {
            setResult(type == 2, mEtInfo.getText().toString().trim());
        }

    }

    // 初始化Eedittext 控件
    private void initEditText() {
        mEtInfo.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int before, int count) {
                if (!resetText) {
                    cursorPos = mEtInfo.getSelectionEnd();
                    // 这里用s.toString()而不直接用s是因为如果用s，
                    // 那么，inputAfterText和s在内存中指向的是同一个地址，s改变了，
                    // inputAfterText也就改变了，那么表情过滤就失败了
                    inputAfterText = s.toString();
                }

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!resetText) {
//                    if (count >= 2) {//表情符号的字符长度最小为2    //(可爱表情count为1)
                    mText = mEtInfo.getText().toString().trim();
                    if (mText == null || start >= mText.length()) {
                        return;
                    }
                    String input = mText.substring(start, mText.length());

//                        EmojiFilter emojiFilter = new EmojiFilter();  //若不判断count,利用这个可以滤掉所有表情,但是count为1的文字也被滤掉了
//                        if (CheckUtils.isEmpty(emojiFilter.filter(input, 0, input.length() - 1, null, 0, 0))) {
//                        if (containsEmoji(input)) {
                    if (isEmoji(input)) {
                        resetText = true;
                        XToastUtils.showShortToast("不支持输入Emoji表情符号");
                        //是表情符号就将文本还原为输入表情符号之前的内容
                        mEtInfo.setText(inputAfterText);
                        CharSequence text = mEtInfo.getText();
                        if (text instanceof Spannable) {
                            Spannable spanText = (Spannable) text;
                            Selection.setSelection(spanText, text.length());
                        }
                    }
//                    }
                } else {
                    resetText = false;
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }


    /**
     * 检测是否有emoji表情(无法滤掉国旗等表情)
     *
     * @param source
     * @return
     */
    public static boolean containsEmoji(String source) {
        int len = source.length();
        for (int i = 0; i < len; i++) {
            char codePoint = source.charAt(i);
            if (!isEmojiCharacter(codePoint)) { //如果不能匹配,则该字符是Emoji表情
                return true;
            }
        }
        return false;
    }

    /**
     * 判断是否是Emoji
     *
     * @param codePoint 比较的单个字符
     * @return
     */
    private static boolean isEmojiCharacter(char codePoint) {
        return (codePoint == 0x0) || (codePoint == 0x9) || (codePoint == 0xA) ||
                (codePoint == 0xD) || ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) ||
                ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) || ((codePoint >= 0x10000)
                && (codePoint <= 0x10FFFF));
    }

    //该正则可以有效过滤Emoji表情符号,无需判断count
    public boolean isEmoji(String string) {
        Pattern p = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",
                Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(string);
        return m.find();
    }
}
